import { ref, toRefs, reactive } from "vue"
import Point from "../../../zondy/lib/Point.js"
import createDraw from "../../../zondy/lib/draw.js"
import { useMapStore } from "../../store/useMap.js"
const { mapState } = toRefs(useMapStore())
export const useAddEvent = () => {
  const draw = ref(null)
  const addEventsource = ref(null)
  const addEventlayer = ref(null)
  const addEventEle = ref(null)
  const addEventService = { name: "traffic", layerId: 2 }
  const addEventForm = reactive({
    eventNumber: "",
    dirverName: "",
    carNumber: "",
    eventPlace: "",
    eventDate: "",
    eventGrade: "",
    eventType: "",
  })
  const addDialogEvent = ref(false)
  const addPosition = ref([])
  addEventsource.value = new ol.source.Vector({ wrapX: false })
  addEventlayer.value = new ol.layer.Vector({
    source: addEventsource.value,
  })
  function addEvent() {
    draw.value = createDraw({ source: addEventsource.value, type: "Point" })
    mapState.value.map.addInteraction(draw.value)
    draw.value.on("drawend", endAddEvent, this)
  }
  function endAddEvent(e) {
    addPosition.value = e.feature.getGeometry().getCoordinates()
    addDialogEvent.value = true
  }
  function confirmAddEvent() {
    Point.add({
      position: addPosition.value,
      attr: [addEventForm.eventNumber, addEventForm.eventType, addEventForm.eventGrade, addEventForm.eventDate, addEventForm.eventPlace, addEventForm.carNumber, addEventForm.dirverName, "0", "0"],
      service: addEventService,
      docLayer: mapState.value.docLayer,
    })
    addDialogEvent.value = false
    addEventEle.value.resetFields()
  }
  function cancelAddEvent() {
    addDialogEvent.value = false
    addEventEle.value.resetFields()
    return
  }
  function cancelAddDraw() {
    addEventsource.value.clear()
    mapState.value.map.removeLayer(addEventlayer.value)
    mapState.value.map.removeInteraction(draw.value)
  }
  return { addEvent, addEventForm, addDialogEvent, confirmAddEvent, cancelAddEvent, addEventEle, cancelAddDraw }
}
